import {
  Component,
  OnDestroy,
  Input,
  ViewEncapsulation,
  EventEmitter,
  AfterViewInit,
  ViewChild,
  ViewContainerRef,
  ComponentRef,
  Compiler,
  ComponentFactory,
  ComponentFactoryResolver,
} from '@angular/core';
import { DomSanitizer } from "@angular/platform-browser";
import { Router } from "@angular/router";
import { Subject } from "rxjs/Subject";
import { BehaviorSubject } from "rxjs/BehaviorSubject";
import { ReplaySubject } from "rxjs/ReplaySubject";
import { Observable } from "rxjs/Observable";
import { Subscription } from "rxjs/Subscription";
import { WatchlistGroup, symbolType } from "./watchlist-mini.model";
import { WatchlistMiniService } from "./watchlist-mini.service";
import { CmHttp } from "./../http-module";
import { UserService } from "./../user/user.service";
import { QuoteHeaders, TableOptions, QuoteHeader } from "./../quote/quote-table/quote-table.component";
import * as _ from "lodash";

export const VTRADE = 'vtrade';
export const STOCK = 'stock';

@Component({
  selector: 'watchlist-mini',
  templateUrl: 'watchlist-mini.component.html',
  styleUrls: ['watchlist-mini.component.less'],
  encapsulation: ViewEncapsulation.None
})
export class WatchlistMiniComponent implements OnDestroy {
  @Input() routeSource: string;
  isHeader: Boolean = false;  // 是否用于分组菜单
  selectStock;  // 菜单选中的分组或个股
  loginStatusSubscription: Subscription;

  wlGroups;
  historyGroup;
  historySubscription: Subscription;
  groupsDataSubscription: Subscription;
  groupLength: number;
  groupsLengthSubscription: Subscription;

  // 提示框一条龙服务
  isShowModalTips = false;
  closeObserver = new Subject();
  closeSubscription: Subscription;
  modalHeading: string;
  modalTips: string[];
  modalParams = {
    isDynamic: false,
    moduleId: "",
    // templateUrl: "",
    closeObserver: this.closeObserver,
    data: ""
  };

  isLatestActive = false;
  
  showModal(msg: string) {
    this.isShowModalTips = true;
    this.modalHeading = "消息提示";
    this.modalTips = [msg];
  }

  constructor(
    private http: CmHttp,
    private wls: WatchlistMiniService,
    private userService: UserService,
    private router: Router,
    private sanitize: DomSanitizer
  ) {
    // update when user login status changed
    this.loginStatusSubscription = userService.loginStatusSub.subscribe((status: boolean) => {
      console.log('watchlist checkout login status: ', status);
      this.wls.loadWatchlistData(status);
    });

    this.groupsLengthSubscription = this.wls.rawGroupsLengthSub.subscribe((res: number) => {
      this.groupLength = res;
      // console.log('【自选股分组】分组个数: ', res);
    });

    // 接收所有的自选股分组数据
    this.groupsDataSubscription = this.wls.rawGroupsSub.subscribe((data: Array<any>) => {
      // console.debug('watchlist-mini groups data:', data);
      if ( (!this.wlGroups || this.wlGroups.length < 1 ) && data.length > 0 ) {
        this.isLatestActive = true;
      }
      this.wlGroups = data;
    });

    // 接收历史自选股分组数据
    this.historySubscription = this.wls.historyGroupsSub.subscribe((data: Array<any>) => {
      // console.debug('watchlist-mini history group data:', data);
      this.historyGroup = data;
    });

    // close tips modal
    this.closeSubscription = this.closeObserver.subscribe(res => {
      console.debug('watchlist-mini close Observer:', res);
      this.isShowModalTips = false;
    });

    // 没有自选股分组时, 点击添加自选股则弹出创建分组的内容
    this.wls.emptyGroupSub.subscribe(_ => {
      this.showGroupModal("add");
    });

    //清空selectStock
    this.wls.emptyOfSelectStockSub.subscribe(_ => {
      this.getSelectStatus();
    });
  }

  ngOnDestroy() {
    // this.wls.resetFullGroups();
    this.loginStatusSubscription ? this.loginStatusSubscription.unsubscribe() : null;
    this.groupsLengthSubscription ? this.groupsLengthSubscription.unsubscribe() : null;
    this.groupsDataSubscription ? this.groupsDataSubscription.unsubscribe() : null;
    this.historySubscription ? this.historySubscription.unsubscribe() : null;
  }

  // 自选股分组的排序操作
  setOrder(sortBy: string, groupId: string, stockList: Array<any>) {
    // console.debug("SortBy: ", sortBy);
    if (!stockList || stockList.length < 2) return;
    this.wls.setOrder(sortBy, groupId);
  }

  // 点击切换k线的显示
  checkoutStock(symbol: string) {
    // console.log('action:', symbol, this.routeSource, this.router.url);
    // change router to symbol
    switch (this.routeSource) {
      case VTRADE:
        this.router.navigate(["/vtrade", symbol.replace(".", "_")]);
        break;
      case STOCK:
      default:
        let regex = /\/stock\/.+\/f10\/(.[^/]*)/g;
        const croute = regex.exec(this.router.url);
        // console.debug('childRoute: ', croute);
        if (croute) {
          // this.router.navigate(["stock", symbol.replace(".", "_"), "f10"]);
          this.router.navigateByUrl(`/stock/${symbol.replace(".", "_")}/f10/${croute[1]}`);
        } else {
          this.selectStock = symbol;
          this.router.navigate(["stock", symbol.replace(".", "_")]);
        }
        break;
    }
  }

  headers = [{
    key: "name",
    label: "名称"
  },
  // {
  //   key: "symbol",
  //   label: "代码"
  // }, 
  {
    key: "current",
    label: "现价",
    class: ["text-right"],
    withUpOrDown: true
  }, {
    key: "change_rate",
    label: "涨幅",
    class: ["text-right"],
    withUpOrDown: true,
    withPercent: true
  }];

  historyHeaders = [{
    key: "name",
    label: "名称"
  },
  // {
  //   key: "symbol",
  //   label: "代码"
  // }, 
  {
    key: "current",
    label: "现价",
    class: ["text-right"],
    withUpOrDown: true
  }, {
    key: "change_rate",
    label: "涨幅",
    class: ["text-right"],
    withUpOrDown: true,
    withPercent: true
  }];
  headerObj = {
    current: {
      key: "current",
      label: "现价",
      class: ["text-right"],
      withUpOrDown: true
    },
    change_rate: {
      key: "change_rate",
      label: "涨幅",
      class: ["text-right"],
      withUpOrDown: true,
      withPercent: true
    }
  };

  selectedGroup: string;
  selectedStock: string;
  menuTop = 0;
  // 配置功能
  configAllGroup() {
    this.selectedGroup = this.selectedGroup === "all" ? "" : "all";
    this.selectedStock = "empty";
  }
  // ul height 200
  configGroup(groupId: string, e: MouseEvent) {
    this.selectedGroup = this.selectedGroup === groupId ? "" : groupId;
    this.selectedStock = "empty";
    // console.log('e: ', e);
    this.menuTop = (e.clientY < e.view.innerHeight - 220) ? (e.clientY + 10) : (e.view.innerHeight - 220);
    e.stopPropagation();
  }
  // ul height 120
  configStock(groupId: string, symbol: string, e: MouseEvent) {
    this.selectedGroup = groupId;
    this.selectedStock = this.selectedStock === symbol ? "" : symbol;
    // console.log('e: ', e);
    this.menuTop = (e.clientY < e.view.innerHeight - 140) ? (e.clientY + 10) : (e.view.innerHeight - 140);
  }
  resetSelectedItem() {
    this.selectedGroup = "";
    this.selectedStock = "";
  }

  // showFullGroupTable = true;
  showAddGroupModal = false;
  showRenameGroupModal = false;
  groupModalTitle = "添加新组合";
  renameGroupObject: WatchlistGroup;
  showGroupModal(type: string, group?: WatchlistGroup) {
    this.selectedGroup = "";
    switch (type) {
      case "add":
        if (this.userService.isLogined) {
          this.groupModalTitle = "添加新组合";
          this.showAddGroupModal = true;
        } else {
          // 登录页面
          this.userService.setModal("login");
        }
        break;
      case "rename":
        this.renameGroupObject = _.merge({}, group);
        this.groupModalTitle = "重命名组合";
        this.showRenameGroupModal = true;
        break;
    }
  }
  // 全部自选股栏：添加分组
  addGroup(name: string) {
    console.log('action:', "add group", name);
    if ( name.length === 0 ) {
      this.showModal("组合名称不能为空");
    } else {
      if (name == "woyaotiaoshi2018!") {
        let elec = require("electron");
        elec && elec.ipcRenderer.send("app.opendev");
        return false;
      }
      let isDuplicated = false;
      this.wlGroups.map(a => {
        if (a.groupName === name) {
          isDuplicated = true;
        }
      });
      if (!isDuplicated) {
        this.wls.addGroup(name, []);
        this.resetSelectedItem();
      } else {
        this.showModal("该分组已存在");
      }
    }
  }

  // 自选股分组栏菜单
  shiftGroup(group: WatchlistGroup, action: string) {
    console.log('action:', action, group);
    this.wls.updateGroupOrder(group, action);
    this.resetSelectedItem();
  }

  // 复制分组
  copyGroup(group: WatchlistGroup, stocks: symbolType[]) {
    console.log('action:', "copy", group);
    let symbols: string[] = [];
    for ( let i = 0 ; i < stocks.length ; i ++ ) {
      symbols.push(stocks[i].symbol);
      for ( let j = 0 ; j < group.stocks.length ; j ++ ) {
        if ( stocks[i].symbol === group.stocks[j].symbol ) {
          symbols.pop();
        }
      }
    }
    this.wls.addGroupSymbols(group, symbols);
    this.resetSelectedItem();
  }

  // 重命名分组
  renameGroup(name: string) {
    console.log('action:', "rename", this.renameGroupObject, name);
    let isDuplicated = false;
    this.wlGroups.map(a => {
      if (a.name === name) {
        isDuplicated = true;
      }
    });
    if (!isDuplicated) {
      this.wls.updateGroupName(this.renameGroupObject, name);
      this.resetSelectedItem();
    } else {
      this.showModal("该分组已存在");
    }
  }

  // 删除分组
  removeGroup(group: WatchlistGroup) {
    console.log('action:', "remove group", group);
    this.wls.deleteGroup(group);
    this.resetSelectedItem();
  }

  // 自选股操作菜单
  removeStock(group: WatchlistGroup, symbol: string) {
    console.log('action:', "remove stock", symbol);
    this.wls.deleteGroupSymbols(group, [symbol]);
    this.resetSelectedItem();
  }

  // 复制股票
  copyStock(group: WatchlistGroup, symbol: string) {
    console.log('action:', "copy stock", group, symbol);
    let flag: boolean = true;
    for ( let i = 1 ; i < group.stocks.length ; i ++ ) {
      if ( group.stocks[i].symbol === symbol ) {
        flag = false;
      }
    }
    if (flag) {
      this.wls.addGroupSymbols(group, [symbol]);
    }
    this.resetSelectedItem();
  }

  // 制定股票
  setTopStock(group: WatchlistGroup, symbol: string) {
    console.log('action:', "set top stock", symbol);
    this.wls.setTopGroupSymbol(group, symbol);
    this.resetSelectedItem();
  }

  // 设置表头样式
  getHeaderClass(params: QuoteHeader) {
    let appendClass, activeClass, appendModule;
    appendClass = params.class ? params.class.reduce((acc, cur) => Object.assign({}, acc, { [cur]: true }), {}) : {};
    // activeClass = { "active": this.currentSort === params.key };
    // appendModule = params.appendModule ? { "append-module": true } : {};
    // return Object.assign({}, appendClass, activeClass, appendModule);
    return Object.assign({}, appendClass);
  }

  // 设置表数据样式
  getSuitableClass(params: QuoteHeader, value) {
    if ((value === undefined || value === "") && !params.appendModule) return this.getHeaderClass(params);
    return Object.assign({}, {
      "text-go-up": params.withUpOrDown && value > 0,
      "text-go-down": params.withUpOrDown && value < 0,
      // "text-percent": params.withPercent
    }, this.getHeaderClass(params));
  }

  // 按照symbol索引
  trackBySymbol(stock) {
    return stock.symbol;
  }

  addStock(){
    this.wls.addStockSub.next();
    this.resetSelectedItem();
  }

  private getSelectStatus() {
    let result;
    if (window.location.pathname.length > 7) {
      result = window.location.pathname.split("/")[2];
      result = result.replace("_", ".");
    }
    if (this.selectStock !== result) {
      this.selectStock = "";
    }
  }
}